package com.example.myapplication;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.File;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    Button btnPhoto; // 申明成员变量，保存布局中的按钮
    Button btnTakePhoto;
    ImageView ivPhoto; // 显示图片的ImageVIew
    private Uri imageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        btnPhoto = findViewById(R.id.btn_photo); // 从布局中获取按钮对象
        btnPhoto.setOnClickListener(this);// 设置按钮点击事件监听器

        ivPhoto = findViewById(R.id.iv_photo); // 获取布局中图片控件
        btnTakePhoto = findViewById(R.id.btn_take_photo);
        btnTakePhoto.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_photo:
                // 选取图片，并显示
                Intent intent = new Intent(Intent.ACTION_PICK);// 选择器
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
                startActivityForResult(intent,1001);
                break;
            case R.id.btn_take_photo:
                File file = new File(getExternalCacheDir(),"photo.jpg");
                if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                    imageUri = Uri.fromFile(file);
                }else {
                    imageUri = FileProvider.getUriForFile(
                            this,
                            "com.external.file",
                            file);
                }
                Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent1.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); // 保存文件的位置
                startActivityForResult(intent1,1002);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1001:
                Uri photoUri = data.getData(); // 获取返回的选择对象的uri
                Log.e(TAG, "onActivityResult: "+photoUri.toString() );
                ivPhoto.setImageURI(photoUri); // 将Uri作为图片控件的显示内容
                break;
            case 1002:
           //     Log.e(TAG, "onActivityResult: "+1002+data.getData() );
                ivPhoto.setImageURI(imageUri); // 将Uri作为图片控件的显示内容
                break;
        }

    }
}